package com.aaa.threadsafety;

import java.util.Arrays;

/**
 * @author C-Q
 * @version 1.1.0
 * @Description:
 * 解决线程安全问题中的自动锁
 * synchronized
 * 加锁和释放锁都是自动的
 * @date 2022/11/1
 */
public class SynchronizedDemo {
    private static String [] arr=new String[2];
    private static int index=0;
    private static Object lock=new Object();
    public static void main(String[] args) throws InterruptedException {
        //构造函数中可以为线程提供任务对象Runnable
        //匿名实现类
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    if (arr[index] == null) {
                        arr[index] = "hello";
                        index++;
                    }
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    if (arr[index] == null) {
                        arr[index] = "world";
                        index++;
                    }
                }
            }
        });

        thread1.start();
        thread2.start();
        //不能直接打印，因为main线程可能先执行；
        thread1.join();
        thread2.join();
        System.out.println(Arrays.toString(arr));
    }
}
